package com.mszlu.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.pojo.Article;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Package: com.mszlu.blog.service
 * @ClassName: ThreadService
 * @Author: 陈威
 * @CreateTime: 2021/9/2 13:46
 * @Description:
 */
@SuppressWarnings("all")
@Service
public class ThreadService {

    @Autowired
    StringRedisTemplate redisTemplate;
    LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();


    //期望此操作在线程池执行，不会影响原有的主线程
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        /*int viewCounts = article.getViewCounts();
        Article artivleUpdate = new Article();

        artivleUpdate.setViewCounts(viewCounts + 1);
        updateWrapper.eq(Article::getId, article.getId());
        //形成的sql语句为 update article set viewcount=99 and id=1
        //设置一个 为了在多线程的环境下 线程安全
        updateWrapper.eq(Article::getViewCounts, viewCounts);

        articleMapper.update(artivleUpdate, updateWrapper);*/

        SysUser sysUser = UserThreadLocal.get();
            System.out.println("---------------阅读数,评论数对象持久化-begin----------------");
            ValueOperations<String, String> operations = redisTemplate.opsForValue();


            String viewCount = operations.get(article.getId() + "viewCount");
            String commentCounts = operations.get(article.getId() + "commentCounts");
            article.setCommentCounts(Integer.valueOf(commentCounts));
            article.setViewCounts(Integer.valueOf(viewCount));
            articleMapper.updateById(article);

            System.out.println("---------------阅读数,评论数对象持久化-end----------------");

    }

}